//
//  MasterTableViewController.swift
//  todoApp
//
//  Created by lili on 15/2/4.
//  Copyright (c) 2015年 ll studio. All rights reserved.
//

import UIKit
import MMDrawerController

//import GoogleMobileAds
import iAd

class MasterTableViewController: UIViewController, UITableViewDataSource,UITableViewDelegate,ADBannerViewDelegate{

    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var adBannerView: ADBannerView!
    //@IBOutlet weak var adBannerView: ADBannerView!
    
    
    var showBanner:Bool = true
    var toDoItems:NSMutableArray=NSMutableArray();
    
     override func viewWillAppear(animated: Bool) {
        self.setupData()
        super.viewWillAppear(animated)
        self.tableView.backgroundColor = BACKGROUND_COLOR
    }
    
    func setupData()
    {
        toDoItems = NoteDBManger.shareInstance().queryAllNotes()
        self.tableView.reloadData()
    }
    
    func showRegist()
    {
        self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
    }
    
    func showAddPage()
    {
        self.performSegueWithIdentifier("showAdd", sender: self)
    }
    
    
    func showComments()
    {
       self.performSegueWithIdentifier("showComments", sender: self)
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "setupData", name: "downLoadNoteNotify", object: nil)

        self.title="备忘录"

        self.tableView.registerNib(UINib(nibName: "MainTableViewCell", bundle: nil), forCellReuseIdentifier: "MainTableViewCell")
        //register button
        var userBtn:UIButton = UIButton(type:UIButtonType.Custom)
        userBtn.frame = CGRectMake(0, 0, 40, 40);
        userBtn.setImage(UIImage(named: "menu"), forState:UIControlState.Normal);
        userBtn.addTarget(self, action:"showRegist", forControlEvents: UIControlEvents.TouchUpInside);
        var left1 = UIBarButtonItem(customView: userBtn)
        
        var tagBtn:UIButton = UIButton(type:UIButtonType.Custom)
        tagBtn.frame = CGRectMake(0, 0, 40, 40);
        tagBtn.setImage(UIImage(named: "comments"), forState:UIControlState.Normal);
        tagBtn.addTarget(self, action:"showComments", forControlEvents: UIControlEvents.TouchUpInside);
        var left2 = UIBarButtonItem(customView: tagBtn)
                
       //upload button
        /*var uploadBtn:UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        uploadBtn.frame = CGRectMake(0, 0, 40, 40);
        uploadBtn.setImage(UIImage(named: "c1"), forState:UIControlState.Normal);
        uploadBtn.addTarget(self, action:"prepareUploadNotesToAVOS", forControlEvents: UIControlEvents.TouchUpInside);
        var right1 = UIBarButtonItem(customView: uploadBtn)
*/
        
        //add button
        let addBtn:UIButton = UIButton(type:UIButtonType.Custom);
        addBtn.frame = CGRectMake(0, 0, 40, 40);
        addBtn.setImage(UIImage(named: "add"), forState:UIControlState.Normal);
        addBtn.addTarget(self, action:"showAddPage", forControlEvents: UIControlEvents.TouchUpInside);
        var right2 = UIBarButtonItem(customView: addBtn)
        
        //add buttons to navbar
        //self.navigationItem.leftBarButtonItem = leftItem;
        self.navigationItem.leftBarButtonItems =  [left1,left2]
        //self.navigationItem.rightBarButtonItems = [right2, right1]
        self.navigationItem.rightBarButtonItems = [right2]


        
        self.canDisplayBannerAds=true
        self.adBannerView?.delegate=self
        self.adBannerView?.hidden=true
    }
    
    /*func addADView(){
        
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 44, 0)

        bannerView.adUnitID = "ca-app-pub-3233061999466083/9652764258"
        bannerView.rootViewController = self
        var request = GADRequest()
        bannerView.loadRequest(request)
    }
*/
    
    /*func addADView(){
        
        bannerView= ADBannerView(adType: .Banner)
        
    }
*/
    func bannerViewDidLoadAd(banner: ADBannerView!) {
        self.adBannerView?.hidden=false
    }
    
    func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
        NSLog("%@", error)
    }
    
    func bannerViewActionDidFinish(banner: ADBannerView!) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    
    
    
     func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    
     func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return toDoItems.count;
    }
    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:MainTableViewCell = tableView.dequeueReusableCellWithIdentifier("MainTableViewCell", forIndexPath: indexPath) as! MainTableViewCell
        
        var note:NoteModel! = toDoItems.objectAtIndex(indexPath.row) as! NoteModel
        cell.titleLabel.text = note.noteText
        cell.timeLabel.text = self.getCreateTimeElapse(note.localCreateTime) as String
        //cell的颜色
        cell.backgroundColor = BACKGROUND_COLOR
        cell.textLabel?.textColor=TEXT_COLOR
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        
        var storyBoard: UIStoryboard = self.storyboard!
        
        var detailVC:DetailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController
        
        detailVC.noteId = (toDoItems[indexPath.row] as! NoteModel).noteId
        
        self.navigationController?.pushViewController(detailVC, animated: true)
    }
    
    // MARK: - Navigation

    
//    func prepareUploadNotesToAVOS()
//    {
//        if (NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn") == false)
//        {
//            UIAlertView.showWithTitle("请登录后使用上传功能", message: "", cancelButtonTitle: "确定", otherButtonTitles: [], tapBlock: nil)
//            
//            return;
//        }
//        var tmp = NSMutableArray(array: self.toDoItems)
//        var uploadTmpArray = NSMutableArray()
//        
//        if  let results = self.downLoadNotesFromAVOS(self.userId())
//        {
//            for (index, object) in enumerate(results)
//            {
//                var avosObj:AVObject = object as! AVObject
//                var noteId:NSString = avosObj.objectForKey("noteId") as! NSString
//                
//                for (idx, obj) in enumerate(self.toDoItems)
//                {
//                    var note:NoteModel! = obj as! NoteModel
//                    
//                    if noteId.isEqualToString(note.noteId)
//                    {
//                        //遍历本地是否有此条目，有的话更新
//                        uploadTmpArray.addObject(NSDictionary(objects: [avosObj,note], forKeys: ["avosObj","noteObj"]))
//                        tmp.removeObject(note)
//                    }
//                }
//            }
//        }
//        
//        for (index, note) in enumerate(tmp)
//        {
//            var newNoteObj = AVObject(className: "NoteClass")
//            uploadTmpArray.addObject(NSDictionary(objects: [newNoteObj,note], forKeys: ["avosObj","noteObj"]))
//        }
//        
//        self.showHudWithTitle("开始同步到服务器")
//        self.startUploadData(0, uploadArray: uploadTmpArray)
//    }

    }
